<template>
  <div>
    <li>
      <label>
        <input type="checkbox" :checked="todo.done" @change="checkTodo(todo.id)"/>
        <span v-show="!todo.isEdit">{{ todo.title }}</span>
        <input type="text"
               :value="todo.title"
               v-show="todo.isEdit"
               @blur="editTitle(todo,$event)"
               ref="todoTitle"
        >
      </label>
      <!--      接收到父组件传来的deleteTodo方法 传入要删除todo的id-->
      <button class="btn btn-danger" @click="deleteTodo(todo.id)">删除</button>
      <!--      添加一个编辑功能-->
      <button class="btn btn-edit" @click="editTodo(todo)">编辑</button>
    </li>
  </div>
</template>

<script>
export default {
  name: "TodoItem",
  props: ['todo'],
  methods: {
    deleteTodo(id) {
      this.$bus.$emit('deleteTodo', id);
    },
    checkTodo(id) {
      this.$bus.$emit('checkTodo', id);
    },
    editTodo(todo) {
      if (!Object.prototype.hasOwnProperty.call(todo, 'isEdit')) {
        this.$set(todo, 'isEdit', true);
      } else {
        todo.isEdit = true;
      }
      //在点击编辑的时候input框立即获取焦点(官方方法)
      //nextTick的用法 在下一次的dom更新后执行其回调
      this.$nextTick(function () {
        this.$refs.todoTitle.focus();
      });
      //随便一点的方法 也可以实现 但是不是很规范
      // setTimeout(() => {
      //   this.$refs.todoTitle.focus();
      // });
    },
    editTitle(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) return alert('不好意思 您的内容是空的哦 无法修改');
      this.$bus.$emit('updateTodo', todo.id, e.target.value)
    }
  }
}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover button {
  display: block;
}

li:hover {
  background-color: beige;
}


</style>